<template>
  <div class="app-container">
    <div class="createPost-container">
      <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
        <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
          <el-button
            v-loading="loading"
            style="margin-left: 10px;"
            type="success"
            @click="submitForm"
          >发布</el-button>
          <el-button v-loading="loading" type="warning" @click="draftForm">草稿</el-button>
        </sticky>

        <div class="createPost-main-container">
          <el-row>
            <el-col :span="24">
              <el-form-item style="margin-bottom: 40px;" prop="title">
                <MDinput v-model="postForm.title" :maxlength="100" name="name" required>标题</MDinput>
              </el-form-item>
      
              <div class="postInfo-container">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label-width="60px" label="类型:" class="postInfo-container-item">
                      <el-select v-model="postForm.type">
                        <el-option
                          v-for="(item,index) in noticeType"
                          :key="item"
                          :label="item"
                          :value="index"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="10">
                    <el-form-item label-width="120px" label="发布时间:" class="postInfo-container-item">
                      <el-date-picker
                        v-model="postForm.releaseTime"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        placeholder="发布时间（不输入默认当前时间）"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="6">
                    <el-form-item label-width="90px" label="重要性:" class="postInfo-container-item">
                      <el-rate
                        v-model="postForm.importance"
                        :max="3"
                        :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                        :low-threshold="1"
                        :high-threshold="3"
                        style="display:inline-block"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>

          <el-form-item style="margin-bottom: 40px;" label-width="70px" label="摘要:">
            <el-input
              v-model="postForm.summary"
              :rows="1"
              type="textarea"
              class="article-textarea"
              autosize
              placeholder="请输入内容"
            />
            <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字符</span>
          </el-form-item>

          <el-form-item prop="content" style="margin-bottom: 30px;">
            <Tinymce ref="editor" v-model="postForm.content" :height="800" />
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import MDinput from "@/components/MDinput";
import Tinymce from "@/components/Tinymce";
import Sticky from "@/components/Sticky"; // 粘性header组件
import { validURL } from "@/utils/validate";
import { getNoticeInfo, saveNoticeInfo } from "@/api/gateway/notice";
import { getEnum } from "@/utils/global";

export default {
  name: "NoticeDetail",
  components: { Tinymce, MDinput, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === "") {
        this.$message({
          message: rule.field + "为必传项",
          type: "error"
        });
        callback(new Error(rule.field + "为必传项"));
      } else {
        callback();
      }
    };
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback();
        } else {
          this.$message({
            message: "外链url填写不正确",
            type: "error"
          });
          callback(new Error("外链url填写不正确"));
        }
      } else {
        callback();
      }
    };
    return {
      postForm: {
        title: "",
        type: null,
        releaseTime: "",
        importance: 0,
        summary: "",
        content: "",
        status: null
      },
      loading: false,
      noticeType: null,
      rules: {
        image_uri: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        source_uri: [{ validator: validateSourceUri, trigger: "blur" }]
      },
      tempRoute: {}
    };
  },
  computed: {
    contentShortLength() {
      return this.postForm.summary.length;
    }
  },
  created() {
    this.noticeType = getEnum("saaS.Entity.Enums.NoticeType");
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    }
    this.tempRoute = Object.assign({}, this.$route);
  },
  methods: {
    fetchData(id) {
      getNoticeInfo(id)
        .then(response => {
          this.postForm = response.data;
          this.setTagsViewTitle();
          this.setPageTitle();
        })
        .catch(err => {
          console.log(err);
        });
    },
    setTagsViewTitle() {
      const title = "编辑新闻公告";
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.postForm.id}`
      });
      this.$store.dispatch("tagsView/updateVisitedView", route);
    },
    setPageTitle() {
      const title = "编辑新闻公告";
      document.title = `${title} - ${this.postForm.id}`;
    },
    submitForm() {
      console.log(this.postForm);
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.postForm.status = "published";
          saveNoticeInfo(this.postForm)
            .then(response => {
              this.$notify({
                message: response.message,
                type: response.success,
                duration: 2000
              });
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    draftForm() {
      if (
        this.postForm.content.length === 0 ||
        this.postForm.title.length === 0
      ) {
        this.$message({
          message: "请填写必要的标题和内容",
          type: "warning"
        });
        return;
      }
      this.$message({
        message: "保存成功",
        type: "success",
        showClose: true,
        duration: 1000
      });
      this.postForm.status = "draft";
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea /deep/ {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
